package hihocode;

import java.util.HashMap;
import java.util.Scanner;

public class Offer19Problem2 {

	private long count = 0;
	
	public static void main(String[] args) {
		Offer19Problem2 object = new Offer19Problem2();
		object.getRes();
	}
	
	public void getRes(){
		Scanner scanner = new Scanner(System.in);
		int t = scanner.nextInt();
		for(int testcase = 0; testcase < t; testcase++){
			String string = scanner.next();
			count = 0;
			int length = string.length();
			int[] array = new int[length + 1];
			HashMap<Integer, Integer> map = new HashMap<>(length);
			for(int i = 1; i <= length; i++){
				array[i] = string.charAt(i - 1) - '0';
				map.put(array[i], i);
			}
			long inverse = mergeSort(array, 1, length);
			if(inverse == 0){
				System.out.println(0);
				continue;
			}
			if((inverse & 1) != 0){
				System.out.println(-1);
				continue;
			}
			int step = 0;
			
			for(int i = length; i > 1; i--){
				//获取数字i的index
				int index1 = map.get(i);
				int index2 = map.get(i - 1);
				//如果i - 1的下标位于i之前，那么就不用移动
				if(index2 < index1){
					continue;
				}
//				map.put(i - 1, 0);
				step++;
			}
			if(step >= 4){
				System.out.println(step - 1);
			}else{
				System.out.println(step);
 			}
		}
		scanner.close();
	}
	
	public long mergeSort(int[] array, int low, int high) {
		if (low < high) {
			int middle = (low + high) / 2;
			mergeSort(array, low, middle);
			mergeSort(array, middle + 1, high);
			merge(array, low, middle, high);
		}
		return count;
	}

	public void merge(int[] input, int left, int center, int right) {
		int[] tempArray = new int[right - left + 1];
		int mid = center + 1;
		int temp = left;
		int current = 0;
		while (left <= center && mid <= right) {
			if (input[left] > input[mid]) {
				tempArray[current++] = input[mid++];
				/*
				 * 如果input[left]>input[mid]，那么表明下标为left~center的值都会比input[mid]大;
				 * (5,7,8)(4,9)合并为 3+0+0+0
				 */
				count += center - left + 1;
			} else {
				tempArray[current++] = input[left++];
			}
		}
		// 只会执行一个
		while (left <= center) {
			tempArray[current++] = input[left++];
		}
		while (mid <= right) {
			tempArray[current++] = input[mid++];
		}
		current = 0;
		while (temp <= right) {
			input[temp++] = tempArray[current++];
		}
	}
}
